package com.guli.order.web;

import com.guli.common.exception.NoStockException;
import com.guli.order.service.OrderService;
import com.guli.order.vo.OrderConfirmVo;
import com.guli.order.vo.OrderSubmitVo;
import com.guli.order.vo.SubmitOrderResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;

@Controller
public class OrderWebController {
    @Autowired
    OrderService orderService;

    /**
     * 跳转到订单页
     * @param model
     * @return
     */
    @GetMapping("/toTrade")
    public String toTrade(Model model) {
        OrderConfirmVo orderConfirmVo = orderService.confirmOrder();
        model.addAttribute("confirmOrderData", orderConfirmVo);
        return "confirm";
    }



    /**
     * 下单功能
     * @param orderSubmitVo
     * @return
     */
    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVo orderSubmitVo, Model model, RedirectAttributes redirectAttributes) {
        SubmitOrderResponseVo submitOrderResponseVo = orderService.submitOrder(orderSubmitVo);
        //下单成功来到支付选择页
        System.out.println("orderSubmitVo = " + orderSubmitVo);
        try {
            // 下单失败回到订单确认页重新确认订单信息
            if (submitOrderResponseVo.getCode() == 0) {
                //下单成功来到支付选择页
                model.addAttribute("submitOrderResp", submitOrderResponseVo);
                return "pay";
            } else {
                String msg = "下单失败:";
                switch (submitOrderResponseVo.getCode()) {
                    case 1:
                        msg += "订单信息过期，请刷新再次提交";
                        break;
                    case 2:
                        msg += "订单商品价格发生变化，请确认后再次提交";
                        break;
                    case 3:
                        msg += "库存锁定失败，商品库存不足";
                        break;
                }
                redirectAttributes.addFlashAttribute("msg", msg);
                return "redirect:http://order.gulimall.com/toTrade";
            }
        } catch (Exception ex) {

        }
        return "redirect:http://order.gulimall.com/toTrade";
    }
}
